<?php

namespace doujunyu\utility\ali;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use think\Exception;

/**
 * 阿里云短信
 */
class AliSms
{

    protected $accessKeyId = '';
    protected $accessKeySecret = '';
    protected $client = null;

    protected $sign_name = '';


    public function __construct($access_key_id,$access_key_secret,$sign_name)
    {
        if (!class_exists(Dysmsapi::class)) {
            //composer remove alibabacloud/dysmsapi-20170525
            throw  new  Exception("请先执行 'composer require alibabacloud/dysmsapi-20170525 3.1.0'");
        }
        $this->accessKeyId = $access_key_id;
        $this->accessKeySecret = $access_key_secret;
        $this->sign_name = $sign_name;
        $config = new Config([
            "accessKeyId" => $this->accessKeyId,
            "accessKeySecret" => $this->accessKeySecret,
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $this->client = new Dysmsapi($config);
    }

   

    /**
     * 发送短信
     */
    public function sendCode($template_code,$phone_number, $param_data)
    {
        $sendSmsRequest = new SendSmsRequest([
            "signName" => $this->sign_name,
            "templateCode" => $template_code,
            "phoneNumbers" => $phone_number,
            "templateParam" => json_encode($param_data,JSON_UNESCAPED_UNICODE)
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $result = $this->client->sendSmsWithOptions($sendSmsRequest, $runtime);
            if ($result->body->code == 'OK') {
                return ['',$result->body->bizId];
            } else {
                return [$result->body->message,''];
                
            }
        } catch (\Exception $e) {
            return [$e->getMessage(),''];
        }
    }

}